package com.heer.gymnasium.module.store.views;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.module.advise.beans.AdMainBean;
import com.heer.gymnasium.module.article.views.ArticleActivity;
import com.heer.gymnasium.module.card.views.BuyCardListActivity;
import com.heer.gymnasium.module.coach.views.CoachListActivity;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.adapters.HomeAdapter;
import com.heer.gymnasium.module.main.beans.CategoryBean;
import com.heer.gymnasium.module.main.views.FindFragment;
import com.heer.gymnasium.module.map.views.MapShowActivity;
import com.heer.gymnasium.module.order.views.OrderActivity;
import com.heer.gymnasium.module.reservation.views.ReservationListActivity;
import com.heer.gymnasium.module.speedy.views.SpeedyReservationActivity;
import com.heer.gymnasium.module.store.beans.StoreBean;
import com.heer.gymnasium.module.store.beans.StoreResponseBean;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.gymnasium.util.StringUtils;
import com.heer.gymnasium.util.SystemUtils;
import com.heer.imagepick.DensityUtils;
import com.zhihuiyun.library.bannar.Banner;
import com.zhihuiyun.library.bannar.listener.OnBannerListener;
import com.zhihuiyun.library.commonadapter.QuickTypeAdapter;
import com.zhihuiyun.library.commonadapter.ViewHolder;
import com.zhihuiyun.library.commonadapter.quick.Quick;
import com.zhihuiyun.library.view.MyListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * 店铺详情
 * Created by zy on 2018/1/19.
 */

public class StoreActivity extends BaseActivity {

    private final static int RES_ID_ROOT_LAYOUT = R.layout.layout_store;
    private final static int RES_ID_BANNER_PARENT = R.id.layout_store_banner_ll;
    private final static int RES_ID_BANNER = R.id.layout_store_banner;
    private final static int RES_ID_BANNER_LEFT = R.id.layout_store_arrow_left_fl;
    private final static int RES_ID_BANNER_RIGHT = R.id.layout_store_arrow_right_fl;
    private final static int RES_ID_RACHARGE = R.id.layout_store_racharge_iv;
    private final static int RES_ID_RACHARGE_RL = R.id.layout_store_racharge_rl;

    private final static int RES_ID_FIELD_LIST = R.id.layout_store_field_lv;
    private final static int RES_ID_FIELD_ITEM = R.layout.item_field;
    private final static int RES_ID_FIELD_PANEL = R.id.layout_store_field_rl;
    private final static int RES_ID_FIELD_MORE = R.id.layout_store_area_iv;
    private final static int RES_ID_FIELD_LINE = R.id.item_field_line_v;
    private final static int RES_ID_FIELD_NAME = R.id.item_field_type_tv;
    private final static int RES_ID_FIELD_IMG = R.id.item_field_type_iv;
    private final static int RES_ID_FIELD_QUICK = R.id.item_field_quick_tv;
    private final static int RES_ID_FIELD_ORDER = R.id.item_field_order_tv;
    private final static int RES_ID_ADDRESS_TV = R.id.layout_store_address_tv;

    private final static int RES_ID_PHONE = R.id.layout_store_iphone_fl;
    private final static int RES_ID_INFO = R.id.layout_store_info_ll;
    private final static int RES_ID_BUY_CARD = R.id.layout_store_buy_card_rl;
    private final static int RES_ID_COURSE = R.id.layout_store_course_rl;
    private final static int RES_ID_ADDRESS_PANEL = R.id.layout_store_address_ll;
    private final static int RES_ID_COACH = R.id.layout_store_coach_rl;


    private final static int RES_ID_ITEM_ICON_IV = R.id.item_store_store_icon_iv;
    private final static int RES_ID_ITEM_STADIUM_NAME_TV = R.id.item_store_store_name_tv;
//    private final static int RES_ID_ITEM_STADIUM_DISTANCE = R.id.item_collect_right_bottom_ll;
    private final static int RES_ID_ITEM_STADIUM_ADDRESS_TV = R.id.item_store_store_address_tv;
    private final static int RES_ID_ITEM_RATING = R.id.item_store_ratingbar;
    private final static int RES_ID_ITEM_ICON_PANEL = R.id.item_store_icons_ll;


    private final static int DRAWABLE_COLLECT_WHITE = R.drawable.ic_collect;
    private final static int DRAWABLE_COLLECT_ORANGE = R.drawable.ic_collect_foucs;
    private final static int DRAWABLE_BORDER_BLACK = R.drawable.black_border;


    private final static int FIELD_MIN_SIZE = 3;

    @BindView(RES_ID_BANNER_PARENT)
    View bannerParent;
    @BindView(RES_ID_BANNER)
    Banner banner;
    @BindView(RES_ID_BANNER_LEFT)
    View bannerLeft;
    @BindView(RES_ID_BANNER_RIGHT)
    View bannerRight;
    @BindView(RES_ID_FIELD_LIST)
    MyListView fieldListView;
    @BindView(RES_ID_FIELD_MORE)
    ImageView fieldMore;

    @BindView(RES_ID_ITEM_ICON_IV)
    ImageView ivStadium;
    @BindView(RES_ID_ITEM_STADIUM_NAME_TV)
    TextView tvStadiumName;
//    @BindView(RES_ID_ITEM_STADIUM_DISTANCE)
//    View vDistance;
    @BindView(RES_ID_ITEM_STADIUM_ADDRESS_TV)
    TextView tvDescription;
    @BindView(RES_ID_ADDRESS_TV)
    TextView tvAddress;
    @BindView(RES_ID_ITEM_RATING)
    RatingBar ratingBar;
    @BindView(RES_ID_ITEM_ICON_PANEL)
    LinearLayout imagePanel;


    private ArrayList<CategoryBean> tempCategoryList, totalCategoryList;
    private QuickTypeAdapter fieldAdapter;
    private StoreActivity $this;
    private String storeId, phone;
    private float la, lo;
    private StoreBean bean;

    private boolean canClick = true;
    private List<AdMainBean> bannerList;

    @Override
    protected void init() {
        super.init();
        setContentView(RES_ID_ROOT_LAYOUT);
        $this = this;
        tempCategoryList = new ArrayList<>();
        totalCategoryList = new ArrayList<>();
        bannerList = new ArrayList<>();

        storeId = getIntent().getStringExtra(EXTRA_ID);
        //店铺id非空验证
        if (TextUtils.isEmpty(storeId) || StringUtils.toInt(storeId) == 0) {
            ToastUtil.show(this, "未找到店铺");
            return;
        }

        Quick.init(new Quick.QuickLoad() {
            @Override
            public void load(Context context, String url, ImageView view) {
                ImageUtil.loadUrl(context, url, R.drawable.ic_small_basketball, view);
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        fieldMore.setVisibility(View.GONE);
        titleUtils.setRightImage(DRAWABLE_COLLECT_WHITE, 15);
        titleUtils.setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doFocus();
            }
        });
        fieldListView.setAdapter(fieldAdapter = new QuickTypeAdapter<CategoryBean>($this, tempCategoryList, RES_ID_FIELD_ITEM) {
            @Override
            public void bindData4View(ViewHolder holder, final CategoryBean data, int type, int pos) {
                if (pos == getCount() - 1) {
                    holder.setVisibility(RES_ID_FIELD_LINE, View.GONE);
                } else {
                    holder.setVisibility(RES_ID_FIELD_LINE, View.VISIBLE);
                }
                holder.setText(RES_ID_FIELD_NAME, data.getTitle());
                holder.setImg(context, RES_ID_FIELD_IMG, data.getIcon());

                holder.setLis(RES_ID_FIELD_QUICK, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SpeedyReservationActivity.startActivity($this, data.getId());
                    }
                });

                holder.setLis(RES_ID_FIELD_ORDER, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ReservationListActivity.startActivity($this, data.getId());
                    }
                });
            }
        });
    }

    private void doFocus() {
        if (canClick) {
            canClick = false;
            mAppHelper.apiService().doFocus(FOCUS_TYPE_STORE, storeId).enqueue(new BaseCallback<ApiResponse<String>>() {
                @Override
                public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                    canClick = true;
                    ToastUtil.show($this, response.body().getMsg());
                    loadData();
                }

                @Override
                public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                    super.onFailure(call, t);
                    canClick = true;
                }
            });
        }
    }

    @Override
    protected void loadData() {
        super.loadData();
        getStoreInfoBySid(storeId);
    }

    @OnClick(RES_ID_PHONE)
    public void onDial() {
        SystemUtils.dialNumber($this, phone);
    }

    @OnClick(RES_ID_INFO)
    public void toInfo() {
        StoreDetailActivity.startActivity($this, storeId);
    }

    @OnClick(RES_ID_RACHARGE_RL)
    public void toRacharge() {
        OrderActivity.startActivity($this, OrderActivity.OrderType.from_recharge, storeId, Type.ORDER_RECHARGE);
    }

    @OnClick(RES_ID_BUY_CARD)
    public void toBuyCard() {
        BuyCardListActivity.startActivity($this, storeId);
    }

    @OnClick(RES_ID_COURSE)
    public void toCourseList() {
        CourseListActivity.startActivity($this, storeId);
    }

    @OnClick(RES_ID_ADDRESS_PANEL)
    public void toMap() {
        MapShowActivity.startActvity($this, bean);
    }

    @OnClick(RES_ID_COACH)
    public void toCoachList() {
        CoachListActivity.startActivity($this, storeId);
    }

    @OnClick(RES_ID_FIELD_PANEL)
    public void showMoreField() {
//        if (totalCategoryList.size() > FIELD_MIN_SIZE) {
//            if (tempCategoryList.size() <= FIELD_MIN_SIZE) {
//                tempCategoryList.clear();
//                tempCategoryList.addAll(totalCategoryList);
//                RotateAnimation rotateAnimation = new RotateAnimation(0.0f, +180.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//                rotateAnimation.setDuration(60);
//                rotateAnimation.setFillAfter(true);
//                rotateAnimation.setRepeatCount(0);
//                fieldMore.startAnimation(rotateAnimation);
//            } else {
//                tempCategoryList.clear();
//                tempCategoryList.addAll(totalCategoryList.subList(0, FIELD_MIN_SIZE));
//                RotateAnimation rotateAnimation = new RotateAnimation(+180.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//                rotateAnimation.setDuration(60);
//                rotateAnimation.setFillAfter(true);
//                rotateAnimation.setRepeatCount(0);
//                fieldMore.startAnimation(rotateAnimation);
//            }
//        }
        if (tempCategoryList.size() == 0) {
            tempCategoryList.clear();
            tempCategoryList.addAll(totalCategoryList);
//            RotateAnimation rotateAnimation = new RotateAnimation(0.0f, +180.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//            rotateAnimation.setDuration(60);
//            rotateAnimation.setFillAfter(true);
//            rotateAnimation.setRepeatCount(0);
//            fieldMore.startAnimation(rotateAnimation);
        } else {
            tempCategoryList.clear();
//            RotateAnimation rotateAnimation = new RotateAnimation(+180.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//            rotateAnimation.setDuration(60);
//            rotateAnimation.setFillAfter(true);
//            rotateAnimation.setRepeatCount(0);
//            fieldMore.startAnimation(rotateAnimation);

        }
        fieldAdapter.notifyDataSetChanged();
    }

    /**
     * 详情网络请求
     *
     * @param sid
     */
    private void getStoreInfoBySid(String sid) {
        mAppHelper.apiService().getStadium(sid).enqueue(new BaseCallback<ApiResponse<StoreResponseBean.Item>>() {
            @Override
            public void onSuccess(Call<ApiResponse<StoreResponseBean.Item>> call, Response<ApiResponse<StoreResponseBean.Item>> response) {
                if (response.isSuccessful()) {
                    if (response.code() == 200 && response.body() != null && response.body().getData() != null) {
                        StoreResponseBean.Item responseItem = response.body().getData();
                        initStoreInfo(mapStoreDetail(responseItem));
                        HomeAdapter.bindBannerItem(bannerParent, Glide.with($this), banner, bannerLeft, bannerRight, mapStoreBanner(responseItem));
                        initField(mapField(responseItem));
                    }
                }
            }

            @Override
            public void onTokenTimeOut() {
                LoginActivity.logout($this, LoginActivity.TIME_OUT);
            }
        });
    }

    /**
     * 场地加载数据
     *
     * @param categoryBeans
     */
    private void initField(List<CategoryBean> categoryBeans) {
        totalCategoryList.clear();
        totalCategoryList.addAll(categoryBeans);
        tempCategoryList.clear();
        tempCategoryList.addAll(totalCategoryList);
        fieldMore.setVisibility(View.VISIBLE);
//        if (categoryBeans.size() > FIELD_MIN_SIZE) {
////            fieldMore.setVisibility(View.VISIBLE);
////            tempCategoryList.addAll(totalCategoryList.subList(0, FIELD_MIN_SIZE));
////        } else {
////            fieldMore.setVisibility(View.GONE);
////            tempCategoryList.addAll(totalCategoryList);
////        }
        fieldAdapter.notifyDataSetChanged();
    }

    /**
     * 详情赋值
     *
     * @param storeBean
     */
    private void initStoreInfo(final StoreBean storeBean) {
        la = StringUtils.toFloat(storeBean.getLa());
        lo = StringUtils.toFloat(storeBean.getLo());
        phone = storeBean.getStadiumtel();
        titleUtils.setTitleText(storeBean.getStadiumname());

        ImageUtil.loadUrl($this, storeBean.getStadiumpic(), R.drawable.temp_store_item_icon, ivStadium);
        if (TextUtils.equals("0", storeBean.getFocus_id())) {
            titleUtils.setRightImage(DRAWABLE_COLLECT_WHITE, 15);
        } else {
            titleUtils.setRightImage(DRAWABLE_COLLECT_ORANGE, 15);
        }

        tvStadiumName.setText(storeBean.getStadiumname());
//        vDistance.setVisibility(View.GONE);
        tvDescription.setText(storeBean.getStadiumcontent());
        tvAddress.setText(storeBean.getStadiumaddress());
        ratingBar.setIsIndicator(true);
        ratingBar.setRating(5.0f -StringUtils.toFloat(storeBean.getEval()));
        imagePanel.removeAllViews();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtils.dip2px($this, 15), DensityUtils.dip2px($this, 15));
        layoutParams.setMargins(0, 0, DensityUtils.dip2px($this, 3), 0);
        for (int i = 0; i < storeBean.getCategory().size(); i++) {
            final ImageView imageView = new ImageView($this);
            Glide.with($this).load(storeBean.getCategory().get(i).replace("\\", "/")).into(imageView);
            imageView.setLayoutParams(layoutParams);
            imageView.setBackgroundResource(DRAWABLE_BORDER_BLACK);
            imagePanel.addView(imageView);
        }
    }

    /**
     * 数据源转店铺信息
     *
     * @param data
     * @return
     */
    private StoreBean mapStoreDetail(StoreResponseBean.Item data) {
        StoreBean bean = new StoreBean();
        bean.setStadiumname(data.getStadiumname());
        bean.setStadiumcontent(data.getStadiumcontent());
        bean.setStadiumaddress(data.getStadiumaddress());
        bean.setDistance(data.getDistance() == null ? "0" : data.getDistance());
        bean.setStadiumtel(data.getStadiumtel());
        bean.setStadiumpic(data.getStadiumpic());
        bean.setSid(data.getSid());
        bean.setFocus_id(data.getFocus_id());
        bean.setLa(data.getLa());
        bean.setLo(data.getLo());
        bean.setEval(data.getEval());
        bean.setCategory(data.getCategory());
        $this.bean = bean;
        return bean;
    }

    /**
     * 转换banner数据
     *
     * @param data
     * @return
     */
    private List<AdMainBean> mapStoreBanner(StoreResponseBean.Item data) {
        List<AdMainBean> list = new ArrayList<>();
        if (data.getBanner() != null) {
            for (int i = 0, max = data.getBanner().size(); i < max; i++) {
                AdMainBean ad = new AdMainBean();
                ad.setForeign_id(data.getBanner().get(i).getId());
                ad.setImages(data.getBanner().get(i).getImg());
                ad.setAd_position_id(HomeAdapter.TYPE_ACTIVE_STADIUM);
                list.add(ad);
            }
        }
        bannerList.addAll(list);
        return list;
    }

    /**
     * 场地转换
     *
     * @param responseItem
     * @return
     */
    private List<CategoryBean> mapField(StoreResponseBean.Item responseItem) {
        List<CategoryBean> list = new ArrayList<>();
        if (responseItem.getPlace() != null) {
            for (int i = 0, max = responseItem.getPlace().size(); i < max; i++) {
                CategoryBean bean = new CategoryBean();
                bean.setTitle(responseItem.getPlace().get(i).getCate_name());
                bean.setIcon(responseItem.getPlace().get(i).getIcon());
                bean.setId(responseItem.getPlace().get(i).getCate_id());
                list.add(bean);
            }
        }
        return list;
    }


    public static void startActivity(Context context, String storeId) {
        Intent intent = new Intent(context, StoreActivity.class);
        intent.putExtra(EXTRA_ID, storeId);
        context.startActivity(intent);
    }
}
